const ws = require('nodejs-websocket');

module.exports = class WebSocket {
    constructor(port) {
        this.port = port
        this.sendContent = []
        this.startConnect()
    }
    // TODO: Start connecting
    startConnect () {
        this.server = ws.createServer(conn => {
            // 连接成功后发生信息
            conn.sendText(this.handleJson(this.sendContent))
            // 监听事件
            conn.on('close', (code, reason) => {
                console.log('Close the connection: ', code, reason)
            });
            conn.on('error', (code, reason) => {
                console.log('重新链接...');
            });
        }).listen(this.port)
    }
    // TODO: Disconnect
    disconnectionLink () {
        this.server && this.server.close()
    }
    // TODO: 处理需要转化的序列化JSON数据，防止自身调用自身bug
    handleJson (data) {
        let cache = [];
        data = JSON.stringify(data, function (key, value) {
            if (typeof value === 'object' && value !== null) {
                if (cache.indexOf(value) !== -1) {
                    return;
                }
                cache.push(value);
            }
            return value;
        });
        cache = null;
        return data;
    }
}